import React, { Component } from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheQueryForm from '@/components/TheQueryForm';
import { getDateTime3 } from '@/utils/getDate'
import { apiServicePage, apiServiceModifyState } from "@/request/callServicer/serveList";
import store from "@/store/store"
import _ from 'lodash';
import { ExclamationCircleFilled } from "@ant-design/icons";
import GoBack from "@/components/TheGoBack";
import moment from 'moment';
import "./style.scss";
import { Typography, Input, TreeSelect } from 'antd';
const { TextArea } = Input;


// 服务列表
class Comments extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textArea: "",
      storeId: "",
      sortOrder: {
        fields: '',
        order: ''
      },
      treeValue: "",
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      newColumns: [],
      form_show: true,
      source: false,
      searchOption: [
        {
          field: 'mhcServiceId',
          label: '服务id',
          placeholder: '请输入',
          required: false,
          rules: [],
          type: 'Input',
          defaultValue: ''
        },
        {
          field: 'type',
          label: '服务类型',
          placeholder: '全部',
          required: false,
          rules: [],
          type: 'Select',
          options: [{ value: "", label: '全部' }, { value: 'FEED', label: '喂养' }, { value: 'CARE', label: '洗护' }],
        },
        {
          field: 'city',
          label: '省份/城市/区县',
          placeholder: '请输入',
          required: false,
          rules: [],
          type: 'Input',
          defaultValue: ''
        },
        {
          field: 'status',
          label: '状态',
          placeholder: '全部',
          required: false,
          rules: [],
          type: 'Select',
          options: [{ value: "", label: '全部' }, { value: 'Y', label: '已上架' }, { value: 'N', label: '已下架' }],
        },
      ],
      queryForm: {},
    };
  }

  componentDidMount = async () => {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams.source === "dynamic") {
      this.setState({
        source: true
      })
    }
    if (searchParams && pageNo && pathName == 'comments') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo,
          pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      await this.getData()
    }
    if (searchParams.source === "dynamic") {
      this.setState({
        source: true
      })
    }
  };

  audit(title, id) {
    this.setState({ modelTitle: title, visible: true, storeId: id })
  }

  handleCancel = () => {
    this.setState({ visible: false, storeId: '' });
  };

  // 获取表格数据
  getData = async (values) => {
    let { pageNo, pageSize } = this.state.pageData
    if (values && !_.isEmpty(values.time)) {
      values.startTime = getDateTime3(values.time[0])
      values.endTime = getDateTime3(values.time[1])
      delete values.time
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      let { time, ...form } = { ...this.state.queryForm }
      const params = {
        pageNo,
        pageSize,
        queryForm: { ...form, time }
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'comments',
          ...params
        }
      })
      let res = await apiServicePage({
        pageNo,
        pageSize,
        ...this.state.queryForm,
      })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
      // else if (res.code !== 0) {
      //     message.error(res.codeMessage)
      // }
    })
  };

  //添加
  goAdd() {
    this.props.history.push('/call/serve/serveList/add')
  }
  //查看
  goDetail(id) {
    this.props.history.push('/call/serve/serveList/detail/' + id)
  }
  goEdit(id) {
    this.props.history.push('/call/serve/serveList/edit/' + id)
  }
  //时间排序
  sortTime(time) {
    return moment(time).unix()
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      },
      // source: false
    }, () => {
      this.getData()
    })
  };
  putShelf = async (mhcServiceId, status) => {
    let res = await apiServiceModifyState({ mhcServiceId, status })
    if (res.code === 0 && res.data) {
      React.$message({
        type: "success",
        content: status === 'N' ? "下架成功" : "上架成功"
      })
      this.getData()
    }
  }
  sorterFun = (pagination, filters, sorter) => {
    console.log(sorter.order, 'aaaa');
    this.sortOrder = null
    console.log(this.state.columns, 'sssss');
    this.setState({
      sortOrder: {
        fields: sorter.field,
        order: sorter.order
      }
    })
    delete this.state.queryForm['orderByAsc']
    delete this.state.queryForm['orderByDesc']
    let sortType = sorter.order // 排序类型，正序/倒叙/不排序
    if (sortType) {
      this.state.queryForm[sortType === 'ascend' ? 'orderByAsc' : 'orderByDesc'] = sorter.field
      this.getData()
    } else {
      this.getData()
    }
  }

  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }

  onFormSearch(values) {
    // console.log(values)
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      sortOrder: {
        fields: '', order: null
      },
      // source: false
    }, () => {
      this.getData(values)
    })
  }
  onChange = value => {
    this.setState({ treeValue: value });
  };
  render() {
    const {
      dataSource,
      source,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      visible,
      modelTitle,
    } = this.state;
    const columns = [
      {
        title: "ID",
        dataIndex: "mhcServiceId",
        key: "mhcServiceId",
      },
      {
        title: "服务类型",
        dataIndex: "type",
        key: "type",
        render: (_, render) => {
          return { 'FEED': "喂养", "CARE": "洗护" }[render.type]
        }
      },
      {
        title: "服务地区",
        dataIndex: "serviceArea",
        key: "serviceArea",
        render: (_, render) => {
          return <div className='priceTable'>{render.serviceArea}</div>
        }
      },
      {
        title: "基础价格（元）",
        dataIndex: "price",
        key: "price",
      },
      {
        title: "最近修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        render: (_, render) => {
          return { "Y": "已上架", "N": "已下架" }[render.status]
        }
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (_, render) => {
          return (
            <div>
              <TheButton haspermi={["call:serveList:update"]} onClick={() => this.goEdit(render.mhcServiceId)}>修改</TheButton>
              {render.status === "N" && (
                <TheButton
                  haspermi={["call:serveList:status"]}
                  onClick={() => this.putShelf(render.mhcServiceId, "Y")}
                >
                  上架
                </TheButton>
              )}
              {render.status === "Y" && (
                <TheButton
                  haspermi={["call:serveList:status"]}
                  onClick={() => this.putShelf(render.mhcServiceId, "N")}
                >
                  下架
                </TheButton>
              )}
              <TheButton haspermi={["call:serveList:detail"]} onClick={() => this.goDetail(render.mhcServiceId)}>查看</TheButton>
            </div>
          );
        },
      }
    ]

    return (
      <div className={"p-layout-box commodity-content"}>
        {
          source &&
          <div style={{ marginBottom: "1em" }}><GoBack history={this.props.history} title={"返回动态列表"} />
          </div>
        }

        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >

        </TheQueryForm>
        <TheButton type="primary" haspermi={["call:serveList:add"]} size="middle" onClick={() => this.goAdd()} style={{ width: '80px', marginBottom: '20px' }}>
          新建
        </TheButton>
        <TheTable
          columns={columns}
          dataSource={dataSource}
          onChange={this.sorterFun}
          rowKey={'configCarouselId'}
        >

        </TheTable>
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        <TheDialog
          title={
            <div>
              <ExclamationCircleFilled
                style={{ color: "#FAAD14", marginRight: 10 }}
              />
              {'输入' + modelTitle + '原因'}
            </div>
          }
          width={400}
          visible={visible}
          handleCancel={this.handleCancel}
          handleOk={this.handleOk}
        >
          <TextArea
            onChange={(e) => this.setState({
              textArea: e.target.value
            })}
            allowClear
            autoSize={{ minRows: 6, maxRows: 6 }}
            maxLength={20}
            showCount
          />
        </TheDialog>
      </div>
    );
  }
}

export default Comments;
